<script setup lang="ts">
import {reactive, ref, onMounted} from "vue";
import {ElMessage} from "element-plus";
import router from "@/router";
import {useUserStore} from '@/stores/user'

const userStore = useUserStore()
// 表单响应式数据
let loginForm = reactive({
  username: '',
  password: ''
})
let loginRef = ref()
// 记住密码开关
const rememberMe = ref(false)

// 表单校验规则
let loginRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ]
}
let loading = ref(false) // 注册按钮加载状态

/**
 * 执行登录
 * - 支持“记住密码”：在登录成功时根据开关保存/清除本地用户名与密码
 */
let handleLogin = async () => {
  /**
   * 表单验证函数
   * 该函数用于触发表单验证，并在验证完成后执行回调函数
   * @param {Function} callback - 验证完成后的回调函数
   * @returns {void}
   */
  if (!loginRef.value) return  // 验证表单
  await loginRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loginRef.value.validate(async () => {
      // 验证完成后输出表单数据
      console.log(loginForm)
      try {
        loading.value = true // 显示加载状态
        // 发送注册表单信息
        let result = await userStore.login(
            {
              username: loginForm.username, // 用户名
              password: loginForm.password, // 密码
            }
        )
        // console.log("result:", result)
        if (result.success) {
          // 处理记住密码
          if (rememberMe.value) {
            localStorage.setItem('rememberMe', '1')
            localStorage.setItem('rememberUsername', loginForm.username)
            localStorage.setItem('rememberPassword', loginForm.password)
          } else {
            localStorage.removeItem('rememberMe')
            localStorage.removeItem('rememberUsername')
            localStorage.removeItem('rememberPassword')
          }
          ElMessage.success('登录成功')
          // 跳转到首页
          router.push('/home')
        } else {
          ElMessage.error(result.message)
        }
      } catch (error: any) {
        ElMessage.error(error.message)
      } finally {
        loading.value = false // 隐藏加载状态
      }

    })
  })
}

let goToRegister = async () => {
  // 跳转到注册页面
  await router.push('/register')
}

// 初始化：回填“记住密码”
onMounted(() => {
  const savedFlag = localStorage.getItem('rememberMe') === '1'
  rememberMe.value = savedFlag
  if (savedFlag) {
    const savedUsername = localStorage.getItem('rememberUsername') || ''
    const savedPassword = localStorage.getItem('rememberPassword') || ''
    loginForm.username = savedUsername
    loginForm.password = savedPassword
  }
})
</script>

<template>
  <div class="login">
    <el-form
        ref="loginRef"
        class="login-form"
        :model="loginForm"
        :rules="loginRules"
    >
      <h3 class="title">企业数字化平台管理系统</h3>
      <el-form-item prop="username">
        <el-input
            type="text"
            size="large"
            auto-complete="off"
            placeholder="请输入用户名"
            prefix-icon="User"
            v-model="loginForm.username"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input

            type="password"
            size="large"
            auto-complete="off"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            v-model="loginForm.password"
        >
        </el-input>
      </el-form-item>
      <div class="login-options">
        <el-checkbox v-model="rememberMe" style="margin:0px 0px 25px 0px;">
          记住密码
        </el-checkbox>
        <el-link type="primary" :underline="false">
          忘记密码？
        </el-link>
      </div>
      <el-form-item style="width:100%;">
        <el-button
            @click="handleLogin"
            size="large"
            type="primary"
            style="width:100%;"
        >
          <span>登 录</span>
        </el-button>
      </el-form-item>
      <div class="register-link">
        <span>还没有账号？</span>
        <el-link type="primary" :underline="false" @click="goToRegister">
          立即注册
        </el-link>
      </div>
    </el-form>
    <!-- 底部 -->
    <div class="el-login-footer">
      <span>Copyright © 2013-2025 <a href="#" target="_blank">企业数字化平台管理系统</a> 版权所有.</span>
    </div>
  </div>
</template>

<style scoped lang="scss">

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("@/assets/images/bg.png");
  background-size: cover;

  .login-form {
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 25px 25px 25px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .title {
      margin: 0px auto 30px auto;
      text-align: center;
      color: #707070;
      font-size: 20px;
      font-weight: bold;
    }

    .el-input {
      height: 40px;

      :deep(.el-input__wrapper) {
        padding: 0 15px;
      }
    }

    .login-options {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;
    }

    .register-link {
      text-align: center;
      margin-top: 20px;
      font-size: 14px;
      color: #606266;
    }
  }

  .el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;

    a {
      color: white;
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }
  }
}

</style>
